//
//  M4ProrrogaDetiailViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/28.
//

import UIKit

class M4ProrrogaDetiailViewController: M4BaseViewController {
    
    private var M4ProrrogaChannel: [M4ChannelDataModel] = []
    
    var M4ProrrogaData: M4LoanOrderSonDataModel?
    
    var productName = ""
    
    var M4MainLoanId: Int = 0
    
    var M4ProductItemCode: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        M4NavTitle(M4Title: "Prórroga de préstamo")
        let bgview = UIView()
        bgview.backgroundColor = COLOR_00479D
        view.addSubview(bgview)
        bgview.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(M4NavigationFullHeight()-0.5)
            make.left.right.equalToSuperview()
            make.height.equalTo(180)
        }
        view.addSubview(M4TableView)
        M4TableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(M4NavigationFullHeight())
            make.bottom.equalToSuperview().offset(-M4SafeDistanceBottom())
        }
        if M4ProrrogaData?.RmNOmNgMClM == 1 {
            M4ProrrogaDetailDataSource()
        }
        else {
            M4ProrrogaChannelNet()
        }
    }
    
    override func M4BackClick(sender: UIButton) {
        super.M4BackClick(sender: sender)
        
        self.uploadData()
    }
    
    override func M4CellAction(_ action: M4IDAction) {
        let type = M4PagoAction(rawValue: action.M4ActionType)
        if type == .M4ProrrogaAction {
            let alert = UINib(nibName: "M4ProrrogaConfirmAlertView", bundle: nil).instantiate(withOwner: self).last as! M4ProrrogaConfirmAlertView
            alert.M4ProrrogaFee.text = "$ \(M4String.M4BlankAmount(original: "\(M4ProrrogaData?.Fvap ?? 0)"))"
            let time = (M4ProrrogaData?.SMymy ?? 0) / 1000
            let date = Date(timeIntervalSince1970: TimeInterval(time))
            let formatter = DateFormatter()
            formatter.dateFormat = "dd-MM-yyyy"
            let dateString = formatter.string(from: date)
            alert.M4ProrrogaDateLabel.text = M4ProrrogaData?.WxW7NH ?? ""
            alert.M4ProrrogaConfirmBlock = { [weak self] in
                self?.M4ProrrogaConfirmNet()
            }
            alert.M4AlertViewShow()
        }
        else if type == .M4ChannelAction {
            let code = action.M4ActionData as? String ?? ""
            M4ProrrogaCodeNet(channelCode: code)
        }
    }
    
    private func M4ProrrogaDetailDataSource() {
        M4TableSources.removeAll()
        M4TableSources.append(M4TableViewCellData("M4ProrrogaDetailCell", XIB: true, M4ProrrogaData ?? M4LoanOrderSonDataModel()))
        if M4ProrrogaData?.RmNOmNgMClM == 0 {
            M4TableSources.append(M4TableViewCellData("M4PagoChannelCell", XIB: true, M4ProrrogaChannel))
        }
        M4TableView.reloadData()
    }
    
    private func M4ProrrogaChannelNet() {
        let para: [String : Any] = ["McTPi": "ESP", "QqEuBTPo": M4UserDataManager.m4UserShare.M4Itemcode, "ABSPKCGrmp": M4UserDataManager.m4UserShare.M4Token, "Nsm":M4ProductItemCode]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4channel, .post, params: para)) { model in
            if model.code == 1 {
                let data = model.data as? [[String : Any]]
                self.M4ProrrogaChannel = data?.kj.modelArray(M4ChannelDataModel.self) ?? []
            }
            else {
                self.view.makeToast(model.message, position: .center)
            }
            self.M4ProrrogaDetailDataSource()
        }
    }
    
    private func M4ProrrogaCodeNet(channelCode: String) {
        let para: [String : Any] = ["Vhd": "ESP", "BGONVys": M4UserDataManager.m4UserShare.M4Itemcode, "ZpUlgE": M4UserDataManager.m4UserShare.M4Token, "GVhChbrK":M4MainLoanId, "HemM": channelCode, "DCDf": M4ProductItemCode, "ZUfo": 2, "EyhGSCZAn": M4ProrrogaData?.LpjOv ?? 0]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4repayCode, .post, params: para)) { model in
            if model.code == 1 {
                let data = model.data as? [String : Any]
                let link = data?["tJslhw"] as? String ?? ""
                if link != "" {
                    let htmlVC = M4HtmlWebViewController()
                    htmlVC.M4WebTitle = "Pago"
                    htmlVC.M4WebUrl = link
                    self.navigationController?.pushViewController(htmlVC, animated: true)
                }
            }
            else {
                self.view.makeToast(model.message, position: .center)
            }
        }
    }
    
    private func M4ProrrogaConfirmNet() {
        let para: [String : Any] = ["SYppB": "ESP", "WCEo": M4UserDataManager.m4UserShare.M4Itemcode, "ObPklkLNjjo": M4UserDataManager.m4UserShare.M4Token, "HZwW":M4ProrrogaData?.LpjOv ?? 0]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4confirmProrroga, .post, params: para)) { model in
            if model.code == 1 {
                self.GASd = 1
                self.navigationController?.popViewController(animated: true)
            }
            else {
                self.GASd = 0
                self.view.makeToast(model.message, position: .center)
            }
            
            self.uploadData()
        }
    }
    
    var GASd = 0
    var asdqwrA = 1
    func uploadData() {
        let params: [[String:Any]] = [
            [
                "adga" : 11001,
                "sdqw" : inTime,
                "hgjyj" : Int(Date().timeIntervalSince1970 * 1000) ,
                "fASDW" : productName,
                "SFFF" : M4ProrrogaData?.Fvap ?? 0,
                "GASd" : asdqwrA,
                "asdqwrA" : asdqwrA
            ]
        ]
        M4HiddenPointDataManager.M4UploadHiddenPoint(type: .PayDetail, paramsKey: "SrWGGG", params: params, complete: nil)
    }
    
}
